# coding:utf-8
import os
import shutil
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout, QFrame, QSizePolicy, QStackedWidget, \
    QGridLayout
from qfluentwidgets import (Pivot, qrouter, SegmentedWidget, TabBar, CheckBox, ComboBox,
                            TabCloseButtonDisplayMode, BodyLabel, SpinBox, BreadcrumbBar,
                            SegmentedToggleToolWidget, FluentIcon, PushButton, MessageBoxBase, SubtitleLabel,
                            LineEdit, FlyoutViewBase, Flyout, PrimaryPushButton, FlyoutAnimationType, MessageBox,
                            qconfig)
from app.common.style_sheet import StyleSheet
from .core import MAIN_ATTR_NAMES
from .peizhuang_interface_single import PeizhuangInterface
from .ui_name_mappings import *
from utils import get_abs_path
from app.common.config import cfg


class MyCustomMessageBox(MessageBoxBase):
    """ Custom message box """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.titleLabel = SubtitleLabel('新建配装页')
        self.urlLineEdit = LineEdit()

        self.urlLineEdit.setPlaceholderText('输入配置名称')
        self.urlLineEdit.setClearButtonEnabled(True)

        # 将组件添加到布局中
        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addWidget(self.urlLineEdit)

        # 设置对话框的最小宽度
        self.widget.setMinimumWidth(300)


class CustomFlyoutView(FlyoutViewBase):
    def __init__(self, dir='', parent=None):
        super().__init__(parent)
        self._parent = parent
        self.vBoxLayout = QVBoxLayout(self)
        self.label = BodyLabel('这是一场「试炼」，我认为这就是一场为了战胜过去的「试炼」，\n只有战胜了那些幼稚的过去，人才能有所成长。')

        self.vBoxLayout.setSpacing(5)
        self.vBoxLayout.setContentsMargins(20, 16, 20, 16)

        self.widget1 = QWidget(self)
        self.hBoxLayout = QHBoxLayout(self.widget1)
        self.hBoxLayout.setContentsMargins(20, 10, 20, 10)
        self.hBoxLayout.setSpacing(20)
        self.widget1.setLayout(QHBoxLayout(self.widget1))
        # self.vBoxLayout.addWidget(self.label)

        self.dir = dir
        files = os.listdir(dir)
        for file in files:
            file_name = file.split('.')[0]
            widget = QWidget(self)
            layout = QHBoxLayout(widget)
            layout.setContentsMargins(0, 0, 0, 0)
            btn = PushButton(file_name)
            btn_rm = PushButton('×')
            btn_rm.setMaximumWidth(30)
            btn.file_path = os.path.join(dir, file)
            btn_rm.file_path = os.path.join(dir, file)
            btn.clicked.connect(self._create_win_from_file)
            btn_rm.clicked.connect(self._rm_cfg_file)
            layout.addWidget(btn)
            layout.addWidget(btn_rm)

            self.vBoxLayout.addWidget(widget)

        self.button_create = PrimaryPushButton('Create New')
        self.button_cancel = PrimaryPushButton('Cancel')
        self.button_create.setFixedWidth(100)
        self.button_cancel.setFixedWidth(100)
        self.button_create.clicked.connect(self._create_new)
        self.button_cancel.clicked.connect(self.close)
        self.widget1.layout().addWidget(self.button_create)
        self.widget1.layout().addWidget(self.button_cancel)
        self.vBoxLayout.addWidget(self.widget1)

    def _create_win_from_file(self):
        btn = self.sender()
        file_name = btn.text()
        file_path = btn.file_path
        self._parent._add_tab(file_name, file_path)
        try:
            self.close()
        except:
            pass

    def _create_new(self):
        self._parent._create_new_tab()
        try:
            self.close()
        except Exception as e:
            pass

    def _rm_cfg_file(self):
        btn = self.sender()
        file_path = btn.file_path
        os.remove(file_path)
        self.close()


class MultiLabelPeizhuangInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setObjectName('PeizhuangInterface')
        self.tabCount = 1

        self.tabBar = TabBar(self)
        self.stackedWidget = QStackedWidget(self)
        self.tabView = QWidget(self)
        self.controlPanel = QFrame(self)

        self.movableCheckBox = CheckBox(self.tr('IsTabMovable'), self)
        self.scrollableCheckBox = CheckBox(self.tr('IsTabScrollable'), self)
        self.shadowEnabledCheckBox = CheckBox(self.tr('IsTabShadowEnabled'), self)
        self.tabMaxWidthLabel = BodyLabel(self.tr('TabMaximumWidth'), self)
        self.tabMaxWidthSpinBox = SpinBox(self)
        self.closeDisplayModeLabel = BodyLabel(self.tr('TabCloseButtonDisplayMode'), self)
        self.closeDisplayModeComboBox = ComboBox(self)
        self.controlPanel.hide()

        self.hBoxLayout = QHBoxLayout(self)
        self.vBoxLayout = QVBoxLayout(self.tabView)
        self.panelLayout = QVBoxLayout(self.controlPanel)

        fpath = cfg.lastLoadPZCFG.value
        fname = os.path.basename(fpath)
        self._add_tab(fname, fpath)

        # add items to pivot
        self.__initWidget()

    def __initWidget(self):
        self.initLayout()

        self.shadowEnabledCheckBox.setChecked(True)

        self.tabMaxWidthSpinBox.setRange(60, 400)
        self.tabMaxWidthSpinBox.setValue(self.tabBar.tabMaximumWidth())

        self.closeDisplayModeComboBox.addItem(self.tr('Always'), userData=TabCloseButtonDisplayMode.ALWAYS)
        self.closeDisplayModeComboBox.addItem(self.tr('OnHover'), userData=TabCloseButtonDisplayMode.ON_HOVER)
        self.closeDisplayModeComboBox.addItem(self.tr('Never'), userData=TabCloseButtonDisplayMode.NEVER)
        self.closeDisplayModeComboBox.currentIndexChanged.connect(self.onDisplayModeChanged)
        self.controlPanel.setObjectName('controlPanel')
        StyleSheet.PEIZHUANG_INTERFACE.apply(self)
        self.connectSignalToSlot()


    def connectSignalToSlot(self):
        self.movableCheckBox.stateChanged.connect(
            lambda: self.tabBar.setMovable(self.movableCheckBox.isChecked()))
        self.scrollableCheckBox.stateChanged.connect(
            lambda: self.tabBar.setScrollable(self.scrollableCheckBox.isChecked()))
        self.shadowEnabledCheckBox.stateChanged.connect(
            lambda: self.tabBar.setTabShadowEnabled(self.shadowEnabledCheckBox.isChecked()))

        self.tabMaxWidthSpinBox.valueChanged.connect(self.tabBar.setTabMaximumWidth)

        self.tabBar.tabAddRequested.connect(self.showFlyout)
        self.tabBar.tabCloseRequested.connect(self.removeTab)

        self.stackedWidget.currentChanged.connect(self.onCurrentIndexChanged)

    def initLayout(self):
        self.tabBar.setTabMaximumWidth(200)

        # self.setFixedHeight(280)
        self.controlPanel.setFixedWidth(220)
        self.hBoxLayout.addWidget(self.tabView, 1)
        self.hBoxLayout.addWidget(self.controlPanel, 0, Qt.AlignRight)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)

        self.vBoxLayout.addWidget(self.tabBar)
        self.vBoxLayout.addWidget(self.stackedWidget)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)

        self.panelLayout.setSpacing(8)
        self.panelLayout.setContentsMargins(14, 16, 14, 14)
        self.panelLayout.setAlignment(Qt.AlignTop)

        self.panelLayout.addWidget(self.movableCheckBox)
        self.panelLayout.addWidget(self.scrollableCheckBox)
        self.panelLayout.addWidget(self.shadowEnabledCheckBox)

        self.panelLayout.addSpacing(4)
        self.panelLayout.addWidget(self.tabMaxWidthLabel)
        self.panelLayout.addWidget(self.tabMaxWidthSpinBox)

        self.panelLayout.addSpacing(4)
        self.panelLayout.addWidget(self.closeDisplayModeLabel)
        self.panelLayout.addWidget(self.closeDisplayModeComboBox)

    def addSubInterface(self, widget: QLabel, objectName, text, icon):
        widget.setObjectName(objectName)
        # widget.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.stackedWidget.addWidget(widget)
        self.tabBar.addTab(
            routeKey=objectName,
            text=text,
            icon=icon,
            onClick=lambda: self.stackedWidget.setCurrentWidget(widget)
        )
        qconfig.set(cfg.lastLoadPZCFG, widget.config_path, True)
        self.tabCount += 1

    def onDisplayModeChanged(self, index):
        mode = self.closeDisplayModeComboBox.itemData(index)
        self.tabBar.setCloseButtonDisplayMode(mode)

    def onCurrentIndexChanged(self, index):
        widget = self.stackedWidget.widget(index)
        if not widget:
            return

        self.tabBar.setCurrentTab(widget.objectName())
        # self.setStyleSheet('border-image: url(:/gallery/images/header1.png)')
        qrouter.push(self.stackedWidget, widget.objectName())

    def _add_tab(self, fname, fpath):
        text = fname
        widget = PeizhuangInterface(fpath, parent=self)
        setattr(self, f'widget_{self.tabCount}', widget)
        self.addSubInterface(widget, text, text, ':/gallery/images/Smiling_with_heart.png')

    def _create_new_tab(self):
        if hasattr(self, 'flyout'):
            try:
                self.flyout.close()
            except:
                pass
        w = MyCustomMessageBox(self.window())
        if w.exec_():
            dir = get_abs_path('./AppData/peizhuang/usr')
            filename = w.urlLineEdit.text()
            filepath = os.path.join(dir, filename+'.yaml')
            default_file = os.path.join(get_abs_path('./AppData/peizhuang/default.yaml'))
            shutil.copyfile(default_file, filepath)
            self._add_tab(filename, filepath)

    def showFlyout(self):
        dir = get_abs_path('./AppData/peizhuang/usr')
        w = CustomFlyoutView(dir, self)
        self.flyout = w
        Flyout.make(w, self.tabBar.addButton, self, aniType=FlyoutAnimationType.DROP_DOWN)

    def removeTab(self, index):
        item = self.tabBar.tabItem(index)
        widget = self.findChild(PeizhuangInterface, item.routeKey())
        self.stackedWidget.removeWidget(widget)
        self.tabBar.removeTab(index)
        widget.deleteLater()